//
//  UITextViewExtension.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/4.
//

import UIKit

extension UITextView {
    //添加链接文本（链接为空时则表示普通文本）
    func wn_appendLinkString(string: String, withURLString: String = "") {
        //原来的文本内容
        let attrString: NSMutableAttributedString = NSMutableAttributedString()
        attrString.append(self.attributedText)
        //新增的文本内容（使用默认设置的字体样式）
        let appendString = NSMutableAttributedString(string: string, attributes:[NSAttributedString.Key.font : self.font!])
        //判断是否是链接文字
        if withURLString != "" {
            let range: NSRange = NSMakeRange(0, appendString.length)
            appendString.beginEditing()
            appendString.addAttributes([NSAttributedString.Key.link: withURLString], range:range)
            appendString.endEditing()
        }
        //合并新的文本
        attrString.append(appendString)
        //设置合并后的文本
        self.attributedText = attrString
    }
}

extension UITextView {
    func numberOfLines() -> Int {
        let layoutManager = self.layoutManager
        let numberOfGlyphs = layoutManager.numberOfGlyphs
        var lineRange: NSRange = NSMakeRange(0, 1)
        var index = 0
        var numberOfLines = 0

        while index < numberOfGlyphs {
            layoutManager.lineFragmentRect(forGlyphAt: index, effectiveRange: &lineRange)
            index = NSMaxRange(lineRange)
            numberOfLines += 1
        }
        return numberOfLines
    }
}
